import axios from 'axios';
import Cookie from 'js-cookie';
import { stringify } from 'query-string';
import CONSTANT from '@/public/constant';
import { message } from 'antd';
import router from 'umi/router';
const { domain } = CONSTANT;
type AxiosType = {
    params?: {
        [key: string]: any
    }
    headers?: HeadersType
};
type HeadersType = {
    [key: string]: any
};
export type ResponseType = {
    code: number | string,
    data: any,
    msg: string,
    success: boolean
}


function normalizeContentyType(headers: HeadersType) {
    const contentType = (headers && headers['Content-Type']);
    return contentType || 'application/x-www-form-urlencoded';
}

const showErrorMessage = (data: any) => message.error(data && data.msg ? data.msg : '请求错误', 4)
axios.interceptors.response.use(
    response => {
        const { code } = response.data;
        if (code !== 200) {
            if(code === 500301) {
                Cookie.remove('token');
                router.push('/login');
                return;
            }
            showErrorMessage(response.data);
            return Promise.reject(response.data);
        }
        return response.data;
    },
    error => {
        showErrorMessage(error.data);
        return Promise.reject(error)
    }
)
function setCommonAxiosCinfig() {
    axios.defaults.timeout = 5000;
    axios.defaults.baseURL = domain;
    axios.defaults.headers.common.Accept = 'application/json';
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    axios.defaults.headers.common["token"] = Cookie.get('token');
}
export function get(url: string, config?: AxiosType) {
    setCommonAxiosCinfig()
    return new Promise((resolve, reject) => {
        axios.get(url, config).then(resp => {
            if ((resp as any).code === 200) resolve(resp)
            else reject(resp);
        }).catch(reject)
    });
}

export function post(url: string, config?: AxiosType) {
    setCommonAxiosCinfig()
    let contentType = config && config.headers ? normalizeContentyType(config.headers) : null;
    // @ts-ignore
    let params;
    if(config && config.params) {
        params = config.params
        // delete config.params;
        for(const key in params) {
            if(params[key] == null) delete params[key]
        }
    }
    switch (contentType) {
        case 'application/json':
            // @ts-ignore
            params = JSON.stringify(params);
            break;
        case 'application/x-www-form-urlencoded':
            // @ts-ignore
            params = stringify(params);
            break;
        default:
            break;
    }

    return new Promise((resolve, reject) => {
        axios.post(url, params, config).then((resp) => {
            if (resp && (resp as any).code === 200) resolve(resp)
            else reject(resp);
        }).catch(reject)
    });
}